<?php


namespace app\test\controller;


use app\common\model\User;
use app\common\model\Wechat;
use think\Controller;
use think\Db;

class ResetUser extends Controller
{

    /**
     *  phone 去重
     */
    private function resetPhone()
    {
        $time = time();
        $data = Db::query('select id,tel,from_unixtime(reg_time) reg_time from wechat_backup_07_18_14_43_00.app_user where tel in (select tel from wechat_backup_07_18_14_43_00.app_user where tel is not null group by tel having count(tel) > 1) order by tel;');

        $userModel = new User();
        $phone = [];
        $update = [];
        foreach ($data as $k => $v)
        {
            if (isset($phone[$v['tel']]))
            {
                $update[] = [
                    'id' => $v['id'],
                    'tel' => $v['tel'] . '_' . $phone[$v['tel']] . 'cf',
                ];

                $phone[$v['tel']] = $phone[$v['tel']] + 1;
            } else
            {
                $phone[$v['tel']] = 1;
            }

            if (count($update) >= 500)
            {
                $userModel->saveAll($update);
                $update = [];

                usleep(1000);
            }
        }

        $userModel->saveAll($update);

        echo '任务执行完成->耗时：' . (time() - $time) . '秒';
    }

    /**
     *  unionid 去重
     */
    private function resetUnionid()
    {
        $time = time();
        $data = Db::query('select id,unionid,from_unixtime(create_time) reg_time from wechat_backup_07_18_14_43_00.app_wechat where unionid in (select unionid from wechat_backup_07_18_14_43_00.app_wechat where unionid is not null group by unionid having count(unionid) > 1) order by unionid;');

        $wechatModel = new Wechat();
        $phone = [];
        $update = [];
        foreach ($data as $k => $v)
        {
            if (isset($phone[$v['unionid']]))
            {
                $update[] = [
                    'id' => $v['id'],
                    'unionid' => $v['unionid'] . '_' . $phone[$v['unionid']] . 'cf',
                ];

                $phone[$v['unionid']] = $phone[$v['unionid']] + 1;
            } else
            {
                $phone[$v['unionid']] = 1;
            }

            if (count($update) >= 500)
            {
                $wechatModel->saveAll($update);
                $update = [];

                usleep(1000);
            }
        }

        $wechatModel->saveAll($update);

        echo '任务执行完成->耗时：' . (time() - $time) . '秒';
    }
}
